<template>
	<view class="cart-container">
		<view class="cart-list">
			<view v-for="(item, index) in cartList" :key="index" class="cart-item">
				<view class="item-check">
					<checkbox :checked="item.flag" @tap="toggleSelect(item.cartid,item.flag)"></checkbox>
				</view>

				<view class="item-image">
					<image :src="item.img1" mode="aspectFill"></image>
				</view>

				<view class="item-info">
					<text class="item-name">{{item.proname}}</text>
					<text class="item-price">¥{{item.originprice}}</text>
				</view>

				<view class="item-actions">
					<view class="quantity-control">
						<view class="quantity-btn minus" @tap="decreaseQuantity(item.cartid,item.num)">-</view>
						<view class="quantity-num">{{item.num}}</view>
						<view class="quantity-btn plus" @tap="increaseQuantity(item.cartid,item.num)">+</view>
					</view>
					<view class="delete-btn" @tap="deleteItem(item.cartid)">删除</view>
				</view>

			</view>
		</view>
	</view>
	<view class="cart-footer">
		<view class="footer-check">
			<checkbox :checked="isAllSelected" @tap="handleAllSelect"></checkbox>
			<text>全选</text>
		</view>

		<view class="footer-total">
			<text>合计: ¥{{totalPrice}}</text>
		</view>

		<button class="footer-settle" @tap="">结算({{selectedCount}})</button>
	</view>
</template>
<script setup>
	import {
		useUserStore
	} from '../../stores/user';
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		useRouter
	} from 'vue-router';

	const router = useRouter();
	let cartList = ref([]);

	//获取用户id
	const userStore = useUserStore();
	let userId = userStore.userInfo.userid;
	if (!userId) {
		userId = uni.getStorageSync('userId')
	}
	console.log(userId);

	// 获取token
	let token = uni.getStorageSync('token');
	console.log(token);

	// 获取购物车信息方法
	function getCartHttp() {
		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/list',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				userid: userId
			}
		}).then(res => {
			cartList.value = res.data.data || [];
			console.log(cartList.value);
		})
	}
	getCartHttp();

	// 更改单个商品勾选功能
	function toggleSelect(id, flag) {
		console.log('切换商品勾选状态:', id, flag);
		const newFlag = !flag;
		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/selectone',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				cartid: id,
				flag: newFlag
			}
		}).then(res => {
			console.log('单个商品勾选接口响应:', res);
			if (res.data.code === '200') {
				// 更新本地购物车数据的勾选状态
				const item = cartList.value.find(item => item.cartid === id);
				if (item) {
					item.flag = newFlag;
				}
			} else {
				uni.showToast({
					title: res.data.message || '更新商品勾选状态失败',
					icon: 'none'
				});
			}
		}).catch(err => {
			console.error('更新商品勾选状态失败', err);
			uni.showToast({
				title: '网络错误，更新商品勾选状态失败',
				icon: 'none'
			});
		})
	}

	// 全选状态变量
	let isAllSelected = ref(false);
	// 计算选中的商品数量
	const selectedCount = computed(() => {
		return cartList.value.filter(item => item.flag).length;
	});

	// 计算选中商品的总价
	const totalPrice = computed(() => {
		return cartList.value
			.filter(item => item.flag)
			.reduce((sum, item) => {
				// 确保价格和数量都是数字
				const price = Number(item.originprice) || 0;
				const quantity = Number(item.num) || 0;
				return sum + price * quantity;
			}, 0)
			.toFixed(2); // 保留两位小数
	});
	// 监听购物车列表变化，更新全选状态
	watch(
		() => cartList.value,
		(newCartList) => {
			if (newCartList.length === 0) {
				isAllSelected.value = false;
				return;
			}
			// 检查是否所有商品都被勾选
			isAllSelected.value = newCartList.every(item => item.flag);
		}, {
			deep: true
		}
	);
	// 全选/取消全选功能
	function handleAllSelect() {
		const newType = !isAllSelected.value;
		isAllSelected.value = newType;

		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/selectall',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				userid: userId,
				type: newType
			}
		}).then(res => {
			cartList.value.forEach(item => {
				item.flag = newType;
			})
		})
	}

	// 删除购物车单条数据
	function deleteItem(id) {
		console.log(id);
		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/remove',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				cartid: id
			}
		}).then(res => {
			getCartHttp();
		})
	}

	//减少商品数量
	function decreaseQuantity(id, num) {
		if (num <= 1) {
			return uni.showToast({
				title: '修改失败，数量不能小于1',
				icon: 'error'
			})
		}
		let newNum = num - 1;
		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/updatenum',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				cartid: id,
				num: newNum
			}
		}).then(res => {
			getCartHttp();
		})
	}

	//增加商品数量
	function increaseQuantity(id, num) {
		let newNum = num + 1;
		console.log(newNum);
		uni.request({
			url: 'http://47.94.6.186:3001/api/cart/updatenum',
			method: 'POST',
			header: {
				'Content-type': 'application/json',
				token: token
			},
			data: {
				cartid: id,
				num: newNum
			}
		}).then(res => {
			getCartHttp();
		})
	}
</script>

<style>
	.cart-container {
		display: flex;
		flex-direction: column;
		height: 1000rpx;
		background-color: #f5f5f5;
	}

	.cart-header {
		display: fixed;
		bottom: 80rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.cart-list {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.2s, box-shadow 0.2s;
		flex-wrap: wrap;
	}

	/* 确保在小屏幕上也有足够空间 */
	@media screen and (max-width: 320px) {
		.item-image {
			width: 140rpx;
			height: 140rpx;
		}
	}

	.cart-item:active {
		transform: scale(0.99);
		box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.03);
	}

	.item-info {
		flex: 1;
		margin-right: 140rpx;
	}

	.item-check {
		margin-right: 20rpx;
	}

	.item-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.item-image image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.item-info {
		flex: 1;
		min-width: 0;
	}

	.item-actions {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		margin-left: 10rpx;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		background-color: #f5f5f5;
		border: 1rpx solid #ddd;
		font-size: 36rpx;
	}

	.quantity-btn.minus {
		border-top-left-radius: 8rpx;
		border-bottom-left-radius: 8rpx;
	}

	.quantity-btn.plus {
		border-top-right-radius: 8rpx;
		border-bottom-right-radius: 8rpx;
	}

	.quantity-num {
		width: 80rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-top: 1rpx solid #ddd;
		border-bottom: 1rpx solid #ddd;
		font-size: 28rpx;
	}

	.delete-btn {
		width: 120rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		background-color: #ff4d4f;
		color: #fff;
		border-radius: 8rpx;
		font-size: 28rpx;
	}

	.item-name {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		overflow: hidden;
		font-size: 28rpx;
		line-height: 42rpx;
		margin-bottom: 10rpx;
		color: #333;
		font-weight: 500;
		-webkit-line-clamp: 2;
	}

	.item-price {
		color: #e54d42;
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 6rpx;
	}

	.item-discount {
		color: #888;
		font-size: 24rpx;
	}


	.empty-cart {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx;
	}

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 40rpx;
		opacity: 0.4;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.go-shopping {
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #e54d42;
		color: #fff;
		border: none;
		border-radius: 40rpx;
		font-size: 32rpx;
	}

	.cart-footer {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		z-index: 999;
	}

	/* 调整主容器样式，避免内容被底部固定栏遮挡 */
	.cart-container {
		padding-bottom: 120rpx;
	}

	.footer-check {
		display: flex;
		align-items: center;
	}

	.footer-total {
		font-size: 32rpx;
		font-weight: bold;
	}

	.footer-settle {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #e54d42;
		color: #fff;
		border: none;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
</style>